//go:build linux

package controller

import (
	"context"
	"fmt"
	"godesk/app/model"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"runtime"
	"time"
)

// Base 控制器基类
type Base struct {
	ctx context.Context
}

const (
	SuccessCode = 200
	ErrorCode   = 101
	NoLoginCode = 501
)

// Res 返回结果
type Res struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// res 返回
func (b *Base) res(code int, message string, data interface{}) Res {
	return Res{
		Code:    code,
		Message: message,
		Data:    data,
	}
}

// success 返回成功
func (b *Base) success(data interface{}) Res {
	return b.res(SuccessCode, "操作成功", data)
}

// error 返回错误
func (b *Base) error(message string) Res {
	return b.res(ErrorCode, message, nil)
}

// setCtx 设置上下文对象
func (b *Base) setCtx(ctx context.Context) {
	b.ctx = ctx
}

// db 获取数据库操作对象和数据库初始化
func (b *Base) db() *gorm.DB {
	//打开数据库，如果不存在，则创建
	db, err := gorm.Open(sqlite.Open(fmt.Sprintf("%s/data.db", b.getAppPath())), &gorm.Config{})
	if err != nil {
		panic(any("数据库连接失败"))
	}
	return db
}

// log 增加日志记录
func (b *Base) log(content string) *Base {
	path := b.pathExist(fmt.Sprintf("%s/logs", b.getAppPath()))
	// 创建或打开日志文件
	logFile, err := os.OpenFile(fmt.Sprintf("%s/%s.log", path, time.Now().Format("2006-01-02")), os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)
	if err != nil {
		log.Fatal(err)
	}
	//defer logFile.Close()
	//记录文件路径和行号
	_, file, line, _ := runtime.Caller(1)
	// 初始化日志
	logger := log.New(logFile, "", log.LstdFlags)
	logger.Println(fmt.Sprintf("\n文件路径：%s:%d\n日志内容：%s\n", file, line, content))
	return b
}

// schema 根据model自动建立数据表
func (b *Base) schema() {
	_ = b.db().AutoMigrate(&model.Config{})
}

// getAppPath 获取应用主目录
func (b *Base) getAppPath() string {
	return b.pathExist("/opt/GoDeskFiles")
}

// pathExist 判断文件目录是否存在，不存在创建
func (b Base) pathExist(path string) string {
	_, err := os.Stat(path)
	if err != nil && os.IsNotExist(err) {
		_ = os.MkdirAll(path, os.ModePerm)
	}
	return path
}

// shellCMD 以shell方式运行cmd命令
func (b *Base) shellCMD(cmdStr string, paramStr string) {
	exec.Command(cmdStr, paramStr).Start()
}

// setSystemBackground 设置系统壁纸
func (b *Base) setSystemBackground(path string) {
	// 设置壁纸
	cmd := exec.Command("gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://"+path)
	err := cmd.Run()
	if err != nil {
		log.Fatalf("Error setting wallpaper: %s", err)
	}
}

// httpGet get请求
func (b *Base) httpGet(url string) []byte {
	res, _ := http.Get(url)
	defer res.Body.Close()
	bytes, _ := io.ReadAll(res.Body)
	return bytes
}

// openDir 打开ubuntu目录
func (b *Base) openDir(path string) {
	b.shellCMD("xdg-open", fmt.Sprintf("file://%s", path))
}
